package ma.mindware.mpm.domain.account;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import ma.mindware.met.core.account.Action;
import ma.mindware.met.core.account.User;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.util.TextParseUtil;

public class AccessInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;
	private Set excludeActions = Collections.EMPTY_SET;


	public void init() {
		
	}
	
	public String intercept(ActionInvocation arg0) throws Exception {
		HttpSession httpSession =ServletActionContext.getRequest().getSession();
		Map<String, Object> session = arg0.getInvocationContext().getSession();
		User user=(User) session.get("user");
		String actionName=arg0.getInvocationContext().getName();
		boolean isAjaxRequest="XMLHttpRequest".equals(ServletActionContext.getRequest().getHeader("X-Requested-With"));
		if(excludeActions.contains(actionName)){
			return arg0.invoke();
		}
		if (user==null) {
			return "notLogged";
		} else {
			ArrayList<Action> actions=(ArrayList<Action>) httpSession.getServletContext().getAttribute("actions");
			Integer applicationID=Integer.parseInt(httpSession.getServletContext().getInitParameter("applicationID"));
			/*for(int i=0;i<actions.size();i++){
				if(actionName.startsWith(actions.get(i).getName())){//split action than object, if exist
					String objectDataName=actionName.substring(actions.get(i).getName().length());
					//check if user has right to process this action
					if(user.getApplicationsMap().get(applicationID).getObjectsDataMap().get(objectDataName).getActionsMap().containsKey(actions.get(i).getName())){
						System.out.println("in first if");
						return arg0.invoke();
					}else{//not allowed
						System.out.println("denyAccess");
						return "denyAccess";
					}
				
				}else{//action is not 
					System.out.println("in second if");
					return arg0.invoke();
				}
			}*/
		}
		return arg0.invoke();
	}
	
	public void setExcludeActions(String values) {
        if (values != null) {
                this.excludeActions = TextParseUtil.commaDelimitedStringToSet(values);
        }
}


}
